const express=require('express');
const cookieParser=require('cookie-parser');
const cookieSession=require('cookie-session');
const userService=require('../service/userService');

var router=express.Router();

router.use('/loginPage.html',async function (req,res,next) {
    var user=req.cookies.user;
    if(user==undefined||user=={}){
        console.log('cookies is null!');
        next();
    }else if(user.role=='admin'){
        console.log('role admin isn\' auto login');
        next();
    } else{
        var data=await userService.loginCookie(user);
        console.log('role user auto login!')
        if(data.success){
            req.session.user=data.user;
            res.redirect('/views/pages/user1.html');
            // res.redirect('/index.html');
        }else {
            next();
        }
    }
});

router.use('/pages',function (req,res,next) {
    var user=req.session.user;
    if(user==[]||user=={}||user==undefined||user==''){
        res.redirect('/views/loginPage.html');
    }else {
        next();
    }
});

router.use('/admin',function (req,res,next) {
    var user=req.session.user;
    if(user==[]||user=={}||user==undefined||user==''){
        res.redirect('/views/loginPage.html');
    }else if(user.role=='user'){
        res.redirect('/views/loginPage.html');
    } else {
        next();
    }
});

exports.router=router;